package com.tuyan.aixiang.component;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.tuyan.aixiang.R;
import com.tuyan.aixiang.common.lang.VoidFunction;

import butterknife.BindView;
import butterknife.ButterKnife;

public class VoiceBtn extends RelativeLayout {

    private VoidFunction startListener;

    private VoidFunction stopListener;

    @BindView(R.id.iv_layer_1)
    ImageView ivLayerOne;

    @BindView(R.id.iv_layer_2)
    ImageView ivLayerTwo;

    @BindView(R.id.iv_layer_3)
    ImageView ivLayerThree;

    @BindView(R.id.iv_close)
    ImageView ivClose;

    private VoidFunction closeListener;

    public VoiceBtn(Context context) {
        this(context, null);
    }

    public VoiceBtn(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressLint("ClickableViewAccessibility")
    public VoiceBtn(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View contentView = LayoutInflater.from(context).inflate(R.layout.layout_voice_btn, this);
        ButterKnife.bind(contentView, this);
        ivLayerThree.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                startVoice();
            }
            if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                stopVoice();
            }
            return true;
        });

        ivClose.setOnClickListener(v -> {
            if(null != closeListener) {
                closeListener.call();
            }
            this.setVisibility(GONE);
        });
    }

    public void setListener(VoidFunction startListener, VoidFunction stopListener, VoidFunction closeListener) {
        this.startListener = startListener;
        this.stopListener = stopListener;
        this.closeListener = closeListener;
    }

    private void startVoice() {
        ivLayerOne.setVisibility(VISIBLE);
        ivLayerTwo.setVisibility(VISIBLE);
        if (null != startListener) {
            startListener.call();
        }
    }

    private void stopVoice() {
        ivLayerOne.setVisibility(INVISIBLE);
        ivLayerTwo.setVisibility(INVISIBLE);
        if (null != stopListener) {
            stopListener.call();
        }
    }

}
